import { ipcMain } from "electron";
import { urlDao } from "~/dao";
import { AxiosRequestConfig } from "axios";
import { useRequestText } from "~/lib/http";

ipcMain.handle("/api/url/list", () => {
  return urlDao.query().list();
});

ipcMain.handle("/api/url/add", (_e, paylaod) => {
  const { data } = paylaod;
  return urlDao.insert(data);
});

ipcMain.handle("/api/url/update", async (_e, paylaod) => {
  const { id, data } = paylaod;
  return urlDao.updateById(id, data);
});

ipcMain.handle("/api/url/delete", async (_e, payload) => {
  const { id } = payload;
  return urlDao.deleteById(id);
});

ipcMain.handle("/api/url/test", async (_e, payload) => {
  const { data } = payload;
  const config = {
    baseURL: data.value,
    url: "/",
    method: "GET",
    headers: {} as Record<string, any>,
    auth: {}
  } as AxiosRequestConfig;
  if (data.is_auth) {
    if (data.auth_type === 1) {
      config.auth = {
        username: data.auth_user!,
        password: data.auth_password!
      };
    } else if (data.auth_type === 2) {
      if (data.auth_user) {
        config.headers = {};
        config.headers[data.auth_user] = data.auth_password;
      }
    }
  }
  return useRequestText("", config);
});
